package com.cskaoyan.service;

import com.cskaoyan.bean.model.MarketCart;
import com.cskaoyan.bean.model.MarketGoods;
import com.cskaoyan.bean.model.MarketGoodsExample;
import com.cskaoyan.bean.resp.PageVo;
import com.cskaoyan.mapper.MarketGoodsMapper;
import com.cskaoyan.util.SystemConfig;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.stream.Collectors;

@Service
public class GoodsServiceImpl implements GoodsService{
    ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Autowired
    private MarketGoodsMapper goodsMapper;

    @Autowired
    private CollectService collectService;

    @Autowired
    private IssueService issueService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private GoodsSpecificationService goodsSpecificationService;
    @Autowired
    private GoodsProductService goodsProductService;
    @Autowired
    private GoodsAttributeService goodsAttributeService;
    @Autowired
    private BrandService brandService;


    @Override
    public Map detail(Integer id) {
        MarketGoods info = goodsMapper.selectByPrimaryKey(id);
        FutureTask issueCallableTask = new FutureTask(() -> issueService.listAll());
        FutureTask commentsCallableTask = new FutureTask(() -> commentService.goodsComment(id));
        FutureTask specificationCallableTask = new FutureTask(() -> goodsSpecificationService.list(id));
        FutureTask productListCallableTask = new FutureTask(() -> goodsProductService.list(id));
        FutureTask goodsAttributeListTask = new FutureTask(() -> goodsAttributeService.list(id));
        FutureTask brandCallableTask = new FutureTask(() -> brandService.detail(info.getBrandId()));
        Map<String, Object> data = new HashMap<>();
        executorService.submit(issueCallableTask);
        executorService.submit(commentsCallableTask);
        executorService.submit(specificationCallableTask);
        executorService.submit(productListCallableTask);
        executorService.submit(goodsAttributeListTask);
        executorService.submit(brandCallableTask);
        try {
            // goods的信息
            data.put("info", info);
            // 已经收藏该商品的用户数量
            data.put("userHasCollect", collectService.userHasCollect(id));
            // 后台管理中的通用问题
            data.put("issue", issueCallableTask.get());
            // 商品评论
            data.put("comment", commentsCallableTask.get());
            // 规格列表 goods_specification表 → 注意按照响应结果的格式来封装
            data.put("specificationList", specificationCallableTask.get());
            // 货品信息 goods_product表
            data.put("productList", productListCallableTask.get());
            // 参数信息 goods_attribute表
            data.put("attribute", goodsAttributeListTask.get());
            // 制造商信息
            data.put("brand", brandCallableTask.get());
            // 是否分享
            data.put("share", SystemConfig.isAutoCreateShareImage());
            // 商品分享图片地址
            data.put("shareImage", info.getShareUrl());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        return data;
    }
    public List<MarketGoods> queryByHot(int offset, int limit) {
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andIsHotEqualTo(true).andIsOnSaleEqualTo(true).andDeletedEqualTo(false);
        example.setOrderByClause("add_time desc");
        PageHelper.startPage(offset, limit);

        return goodsMapper.selectByExample(example);
    }

    /**
     * 获取新品上市
     *
     * @param offset
     * @param limit
     * @return
     */
    public List<MarketGoods> queryByNew(int offset, int limit) {
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andIsNewEqualTo(true).andIsOnSaleEqualTo(true).andDeletedEqualTo(false);
        example.setOrderByClause("add_time desc");
        PageHelper.startPage(offset, limit);

        return goodsMapper.selectByExample(example);
    }

    /**
     * 获取分类下的商品
     *
     * @param catList
     * @param offset
     * @param limit
     * @return
     */
    public List<MarketGoods> queryByCategory(List<Integer> catList, int offset, int limit) {
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andCategoryIdIn(catList).andIsOnSaleEqualTo(true).andDeletedEqualTo(false);
        example.setOrderByClause("add_time  desc");
        PageHelper.startPage(offset, limit);

        return goodsMapper.selectByExample(example);
    }

    @Override
    public long count() {
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andDeletedEqualTo(false);
        long count = goodsMapper.countByExample(example);
        return count;
    }

    @Override
    public MarketGoods findById(Integer goodsId) {

        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(example);
        return marketGoods.size() == 1 ? marketGoods.get(0) : null;
    }

    @Override
    public PageVo goodsRelated(Integer id) {

        MarketGoodsExample example = new MarketGoodsExample();
        // todo: 等下构造条件
        // 同属同一个类目的条件
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);
        Integer categoryId = marketGoods.getCategoryId();

        MarketGoodsExample.Criteria criteria = example.createCriteria();
        PageHelper.startPage(1, 6);
        criteria.andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false);
        List<MarketGoods> list = goodsMapper.selectByExample(example);

        PageVo pageVo = PageVo.list(list);
        // 构造完PageVo之后再处理List，如果构造PageInfo放的不是查询的结果，会影响pages和total的值
        // 如果是分页场景就会有有问题
        List<Map> resolvedList = list.stream().map(goods -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", goods.getId());
            map.put("name", goods.getName());
            map.put("brief", goods.getBrief());
            map.put("isHot", goods.getIsHot());
            map.put("isNew", goods.getIsNew());
            map.put("picUrl", goods.getPicUrl());
            map.put("retailPrice", goods.getRetailPrice());
            return map;
        }).collect(Collectors.toList());
        pageVo.setList(resolvedList);

        return pageVo;
    }

    @Override
    public List<MarketGoods> queryByCart(List<MarketCart> carts) {
        List<Integer> goodsIdList = carts.stream().map(MarketCart::getGoodsId).collect(Collectors.toList());

        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andIdIn(goodsIdList).andDeletedEqualTo(false);
        example.setDistinct(true);

        List<MarketGoods> marketGoods = goodsMapper.selectByExample(example);

        return marketGoods;
    }
}
